//
//  UIViewExtension.swift
//  Intersection
//
//  Created by 我骑着蜗牛走天下 on 2025/3/6.
//

import UIKit

@MainActor private var BlurEffectViewKey: UInt8 = 0

extension UIView {
    
    /// 判断当前view 是否有交互事件
    public func hasInteraction() -> Bool {
        let view = self
        // 基础条件
        guard view.isUserInteractionEnabled, !view.isHidden, view.alpha > 0.01 else {
            return false
        }
        
        // 判断是否有启用的手势
        if let gestures = view.gestureRecognizers {
            for gesture in gestures {
                if gesture.isEnabled {
                    return true
                }
            }
        }
        
        // 判断是否是 UIControl 并且绑定了事件
        if let control = view as? UIControl {
            for target in control.allTargets {
                // 检查是否有任何事件绑定
                if let actions = control.actions(forTarget: target, forControlEvent: .allEvents), !actions.isEmpty {
                    return true
                }
            }
        }
        
        // 也可以考虑子视图是否有交互事件（递归）
//        for subview in view.subviews {
//            if viewHasInteraction(subview) {
//                return true
//            }
//        }
        
        return false
    }

    
    
    /// 无限旋转动画,用于加载圆
    public func startInfiniteRotation() {
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnim.fromValue = 0
        rotationAnim.toValue = Double.pi * 2
        rotationAnim.duration = 2.0
        rotationAnim.repeatCount = .infinity // 或 MAXFLOAT
        rotationAnim.isRemovedOnCompletion = false // 防止动画被移除
        self.layer.add(rotationAnim, forKey: "rotationAnimation")
    }
    
    
    
    /// 设置竖向渐变色
    /// -Parameters:
    ///  - colors: 渐变颜色数组
    ///  - locations: 颜色分界点数组（0-1）
    ///  - width: 渐变色宽度
    ///  - y: 渐变色开始坐标，默认0
    public func gradientColor(colors:Array<CGColor> ,locations: Array<NSNumber> = [0,1] ,height: CGFloat,width:CGFloat? = nil, y: CGFloat = 0) -> CAGradientLayer {
        
        let gradientLayer = CAGradientLayer()
        //几个颜色
        gradientLayer.colors = colors

        //颜色的分界点
        gradientLayer.locations = locations
        //开始
        gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
        //结束,主要是控制渐变方向
        gradientLayer.endPoint  = CGPoint.init(x: 0, y: 1.0)
        //多大区域
        let frame = CGRect.init(x: 0, y: y, width: width ?? self.frame.size.width, height: height)
        gradientLayer.frame = frame
        //最后作为背景
        self.layer.insertSublayer(gradientLayer, at: 0)

        return gradientLayer
    }
    
    /// 设置横向渐变色
    /// -Parameters:
    ///  - colors: 渐变颜色数组
    ///  - locations: 颜色分界点数组（0-1）
    ///  - width: 渐变色宽度
    ///  - x: 渐变色开始坐标，默认0
    public func gradientColor(colors:Array<CGColor> ,locations: Array<NSNumber> = [0,1] ,width: CGFloat, x: CGFloat = 0) {
        
        let gradientLayer = CAGradientLayer()
        //几个颜色
        gradientLayer.colors = colors

        //颜色的分界点
        gradientLayer.locations = locations
        //开始
        gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
        //结束,主要是控制渐变方向
        gradientLayer.endPoint  = CGPoint.init(x: 1.0, y: 0)
        //多大区域
        gradientLayer.frame = CGRect.init(x: x, y: 0, width: width, height: self.frame.size.height)
        //最后作为背景
        self.layer.insertSublayer(gradientLayer, at: 0)

        
    }
    
    
    /// 设置渐变色
    /// -Parameters:
    ///  - colors: 渐变颜色数组
    ///  - locations: 颜色分界点数组（0-1）
    ///  - point: 渐变颜色（开始，结束）点 元祖
    ///  - frame: 渐变色区域
    public func gradientColor(colors:Array<CGColor> ,locations: Array<NSNumber>,point:(start:CGPoint,end:CGPoint) ,frame: CGRect) {
        
        let gradientLayer = CAGradientLayer()
        //几个颜色
        gradientLayer.colors = colors

        //颜色的分界点
        gradientLayer.locations = locations
        //开始
        gradientLayer.startPoint = point.start
        //结束,主要是控制渐变方向
        gradientLayer.endPoint  = point.end
        //多大区域
        gradientLayer.frame = frame
        //最后作为背景
        self.layer.insertSublayer(gradientLayer, at: 0)

    }
    
    // 添加圆角
    public func radius(side: UIRectEdge) {
        switch side {
        case .top:
            layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        case .bottom:
            layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        case .left:
            layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        case .right:
            layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
        case .all:
            layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        default:
            break
        }
    }
    
    // 添加圆角
    public func radius(side: UIRectCorner) {
        var maskedCorners: CACornerMask = []
        if side.contains(.topLeft) {
            maskedCorners.insert(.layerMinXMinYCorner)
        }
        if side.contains(.topRight) {
            maskedCorners.insert(.layerMaxXMinYCorner)
        }
        if side.contains(.bottomLeft) {
            maskedCorners.insert(.layerMinXMaxYCorner)
        }
        if side.contains(.bottomRight) {
            maskedCorners.insert(.layerMaxXMaxYCorner)
        }
        layer.maskedCorners = maskedCorners
    }

    
    ///添加圆角边框
    public func borderRadius(view: UIView, Radius: CGFloat, Width: CGFloat, Color: UIColor){
        view.layer.cornerRadius = Radius
        view.layer.masksToBounds = true
        view.layer.borderWidth = Width
        view.layer.borderColor = Color.cgColor
    }

    ///添加圆角阴影
    public func shadow(Radius: CGFloat, Color: UIColor, ShadowRadius:CGFloat, Offset:CGSize, Opacity:Float = 0){
        // 设置圆角
        self.layer.cornerRadius = Radius
        // 阴影颜色
        self.layer.shadowColor = Color.cgColor
        // 阴影半径，默认3
        self.layer.shadowRadius = ShadowRadius
        // 阴影偏移，默认(0, -3)
        self.layer.shadowOffset = Offset
        // 阴影透明度，默认0
        self.layer.shadowOpacity = Opacity
        
    }

    // 添加单边边框
    public func addBorder(side: UIRectEdge, color: UIColor, width: CGFloat,size:CGSize? = nil) {
       let borderLayer = CALayer()
       borderLayer.backgroundColor = color.cgColor
        
       switch side {
       case .top:
           borderLayer.frame = CGRect(x: 0, y: 0, width: size?.width ?? frame.width, height: width)
       case .bottom:
           borderLayer.frame = CGRect(x: 0, y: (size?.height ?? frame.height) - width, width: size?.width ??  frame.width, height: width)
       case .left:
           borderLayer.frame = CGRect(x: 0, y: 0, width: width, height: size?.height ??  frame.height)
       case .right:
           borderLayer.frame = CGRect(x: (size?.width ?? frame.width) - width, y: 0, width: width, height: size?.height ??  frame.height)
       default:
           break
       }
       
       layer.addSublayer(borderLayer)
   }
    
    /// 绘制虚线
    /// start：起点坐标
    /// end：终点坐标
    /// lineWidth：线宽
    /// lineDashPattern：[实线长度=2, 间隙长度=2]
    public func dashedLine(start: CGPoint = .init(x: 0, y: 0),end: CGPoint? = nil,lineWidth: CGFloat = 1,color:UIColor = .gray,lineDashPattern:[NSNumber] = [4,4]){
        // 创建虚线路径（水平方向）
        let startPoint = start // 起点坐标
        let endPoint = end ?? CGPoint(x: self.bounds.maxX, y: 0) // 终点坐标
        
        let path = UIBezierPath()
        path.move(to: startPoint)
        path.addLine(to: endPoint) // 横向直线
        
        // 创建虚线图层
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = color.cgColor // 虚线颜色
        shapeLayer.lineWidth = lineWidth // 线宽
        shapeLayer.lineDashPattern = lineDashPattern // 图案：[实线长度=8, 间隙长度=4]
        
        layer.addSublayer(shapeLayer)
    }
    
    /// 化线
    public func line(start: CGPoint = .init(x: 0, y: 0),end: CGPoint? = nil,lineWidth: CGFloat = 0.25,color:UIColor = .gray){
        // 创建线路径
        let startPoint = start // 起点坐标
        let endPoint = end ?? CGPoint(x: self.bounds.maxX, y: 0) // 终点坐标
        
        let path = UIBezierPath()
        path.move(to: startPoint)
        path.addLine(to: endPoint)
        
        // 创建虚线图层
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = color.cgColor // 线颜色
        shapeLayer.lineWidth = lineWidth // 线宽
        
        layer.addSublayer(shapeLayer)
    }
    
    
    public var blurEffectView: BlurEffectView?{
        get{
            return objc_getAssociatedObject(self, &BlurEffectViewKey) as? BlurEffectView
        }
    }
    
    /// 设置液体玻璃效果
    public func applyBlurEffect(cornerRadius: CGFloat = 12,border: Bool = true,borderColor: UIColor = UIColor.white) {
        
        layer.cornerRadius = cornerRadius
        
        if border {
            layer.borderWidth = 1
            layer.borderColor = borderColor.cgColor
        }
        
//        // 创建一个模糊效果
//        let blurEffect = UIBlurEffect(style: .light)
//        // 创建模糊视图
//        let blurView = UIVisualEffectView(effect: blurEffect)
//        blurView.backgroundColor = .clear
//        blurView.layer.cornerRadius = cornerRadius
//        blurView.layer.masksToBounds = true
//        blurView.frame = bounds
//        blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//        addSubview(blurView)
        
        let blurView = BlurEffectView()
        blurView.blurLevel = 0.4
        blurView.layer.cornerRadius = cornerRadius
        blurView.layer.masksToBounds = true
        blurView.tag = 111
        addSubview(blurView)
        self.sendSubviewToBack(blurView)
        objc_setAssociatedObject(self, &BlurEffectViewKey, blurView, .OBJC_ASSOCIATION_RETAIN)
        
        blurView.translatesAutoresizingMaskIntoConstraints = false
        blurView.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor).isActive = true
        blurView.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor).isActive = true
        blurView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor).isActive = true
        blurView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor).isActive = true
        
        
        // 第一个阴影
        let shadowLayer1 = CALayer()
        shadowLayer1.frame = bounds
        shadowLayer1.shadowPath = UIBezierPath(rect: shadowLayer1.bounds).cgPath
        shadowLayer1.backgroundColor = UIColor(white: 1, alpha: 0.01).cgColor
        shadowLayer1.shadowColor = UIColor.black.cgColor
        shadowLayer1.shadowOffset = CGSize(width: 0, height: 0) // X, Y
        shadowLayer1.shadowOpacity = 0.08 // 8%
        shadowLayer1.shadowRadius = 48 // blur
        shadowLayer1.cornerRadius = cornerRadius
        layer.addSublayer(shadowLayer1)

        // 第二个阴影
        let shadowLayer2 = CALayer()
        shadowLayer2.frame = bounds
        shadowLayer2.shadowPath = UIBezierPath(rect: shadowLayer2.bounds).cgPath
        shadowLayer2.backgroundColor = UIColor(white: 1, alpha: 0.01).cgColor
        shadowLayer2.shadowColor = UIColor.black.cgColor
        shadowLayer2.shadowOffset = CGSize(width: 0, height: 0) // X, Y
        shadowLayer2.shadowOpacity = 0.05 // 5%
        shadowLayer2.shadowRadius = 4 // blur
        shadowLayer2.cornerRadius = cornerRadius
        layer.addSublayer(shadowLayer2)
    }
    
    /// 暂停动画
    fileprivate func pauseAnimation(delay: Double) {
    
        let time = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, 0, 0, 0, { timer in
            let layer = self.layer
            let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
            layer.speed = 0
            layer.timeOffset = pausedTime
        })
        
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    }
    
    /// 继续动画
    fileprivate func resumeAnimation() {
        let pausedTime  = layer.timeOffset
        
        layer.speed = 1.0
        layer.timeOffset = 0
        layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    }
    
}


open class BlurEffectView: UIVisualEffectView {
    
    /// 模糊等级 （0 ~ 1）
    open var blurLevel: Float = 1 {
        didSet {
            
            self.resumeAnimation()
            
            var blurEffect: UIVisualEffect
            if let effect = self.effect {
                blurEffect = effect
            } else {
                blurEffect = UIBlurEffect(style: .extraLight)
            }
            
            self.effect = nil
            
            UIView.animate(withDuration: TimeInterval(1 - blurLevel)) {
                self.effect = blurEffect
            }
            
            self.pauseAnimation(delay: 0.3)
        }
    }
    
}
